/**
 * Created by liang.zc on 2018/1/26.
 */

/*
import { Base64 } from "js-base64";
import {DCTP, DCTPAPI} from "src/assets/js/lib";
*/
import that from "./api"

let Datafeeds = {};


Datafeeds.WebSocket = function (datafeed, successCallback) {
    this._datafeed = datafeed;
    this._successCallback = successCallback;
    this.duration = 60000; // 重连时间间隔
    this.model = null; // socket
    this.reconnectTimes = 0; // 记录重连次数
    this.clientTimeout = null;
    this.serverTimeout = null;
    this.autoReconnect = true; // socket关闭后是否自动重连
    this.create();
};

Datafeeds.WebSocket.prototype = {
    // 以下socket操作是实时交易的
    reset() {
        this.reconnectTimes = 0;
        this.clientTimeout && clearTimeout(this.clientTimeout);
        this.serverTimeout && clearTimeout(this.serverTimeout);
        this.start();
    },
    start() {
        let _this = this;

        this.clientTimeout = setTimeout(function () {
            _this.send();
            _this.serverTimeout = setTimeout(function () {
                if (_this.model) {
                    _this.model.close();
                } else {
                    _this.create();
                }
            }, _this.duration);
        }, this.duration);
    },
    create() {

        let _this = this;
        if (!window.WebSocket) {
            window.WebSocket = window.MozWebSocket;
        }

        if (window.WebSocket) {
            let model = new window.WebSocket("wss://tstsocket.uutaka.com/");
            model.onopen = event => {

                _this.reconnectTimes++;
                _this.start();
                _this.send();
            };

            model.onclose = event => {
                this.model = null;
                if (_this.autoReconnect && _this.reconnectTimes < 100) {
                    _this.create();
                }
            };

            model.onmessage = data => {



                if (data && data.data) {
                    data = data.data;
                    let dataJson = JSON.parse(data);

                  if(dataJson.params!=undefined&&dataJson.params[0].BCHUSDT){
                     let newDate = new Date();

                    this.api.klineLastData({
                      needTickers:1,
                      symbol:'zbqc',
                      type:'1min',
                      size:1000
                    }).then(res=>{
                       // console.log(res.datas.data[res.datas.data.length-1])
                      _this._onRealtimeCallback({
                        time: res.datas.data[res.datas.data.length-1][0],
                        open: res.datas.data[res.datas.data.length-1][1],
                        close: res.datas.data[res.datas.data.length-1][4],
                        high:res.datas.data[res.datas.data.length-1][2],
                        low:res.datas.data[res.datas.data.length-1][3],
                        volume:res.datas.data[res.datas.data.length-1][5]
                      })
                    },res=>{
                     // console.log(res)
                    })

                  }
				      /*	let symbolInfo = _this._symbolInfo;

                    if (data && data.virtualCurrencyBo && symbolInfo &&
						symbolInfo.ticker === data.virtualCurrencyBo.virtualCoinId) {

                        if (data.type === 1) {
                            _this._successCallback(data);

                            if (data.timeLine) {
                                if (_this._interval !== undefined &&
                                    data.timeLine.dateWeek === _this._interval) {
                                    if (typeof this._onRealtimeCallback === "function") {
                                        this._onRealtimeCallback({
                                            time: data.timeLine.timeStamp,
                                            open: data.timeLine.openPrice,
                                            close: data.timeLine.closePrice,
                                            high: data.timeLine.highPrice,
                                            low: data.timeLine.lowPrice,
                                            volume: data.timeLine.totalNumber
                                        })
                                    }
                                }
                            }
                        }

                    }*/
                }
            };

            this.model = model;
        } else {
            console.log("当前浏览器不支持WebSocket");
        }
    },
    send(symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback) {
        if (symbolInfo !== undefined) {
            this._symbolInfo = symbolInfo;
        }
        if (resolution !== undefined) {
            this._resolution = resolution;
            this._interval = this._datafeed.getStepByResolution(resolution);
        }
        if (onRealtimeCallback !== undefined) {
            this._onRealtimeCallback = onRealtimeCallback;
        }
		if (subscriberUID !== undefined) {
			this._subscriberUID = subscriberUID;
		}
		if (onResetCacheNeededCallback !== undefined) {
			this._onResetCacheNeededCallback = onResetCacheNeededCallback;
		}
      this.model.send('{"activityId":"63","msgType":"reqMsgPartitionActivity","userId":"bd2b700b-63eb-4b91-9de6-66eb2b647879"}');
        /*if (this.model) {
            if (this.model.readyState === window.WebSocket.OPEN) {
                if (this._symbolInfo && this._symbolInfo.ticker) {
                    let data = {
                        userId: DCTP.session.get("userId"),
                        token: DCTP.session.get("token"),
                        type: 1,
                        virtualCoinId: this._symbolInfo.ticker
                    };

                    data = JSON.stringify(data);
                    data = Base64.encode(data);


                }
            }
        }*/
    },
    destroy() {
        if (this.model) {
            this.autoReconnect = false;
            this.model.close();
        }

        this.autoReconnect = true;
    }
};

Datafeeds.UDFCompatibleDatafeed = function(symbolInfo, successCallback) {

  this._configuration = undefined;

    this._symbolInfo = symbolInfo;
    this._socket = new Datafeeds.WebSocket(this, successCallback);

    this._enableLogging = false;
    this._initializationFinished = false;
    this._callbacks = {};

    this._initialize();
};

Datafeeds.UDFCompatibleDatafeed.prototype.defaultConfiguration = function() {

    return {
        supports_search: false,
        supports_group_request: true,
        supported_resolutions: this._symbolInfo.supported_resolutions,
        supports_marks: false,
        supports_timescale_marks: false,
		    supports_time: false
    };
};
//当图表需要知道服务器时间时，如果配置标志supports_time设置为true，则调用此函数。
Datafeeds.UDFCompatibleDatafeed.prototype.getServerTime = function(callback) {
	console.log("call history");

	/*if (this._configuration.supports_time) {
		DCTPAPI.trade_getServerTime({
            success(result) {
                if (result.result) {
                    callback(result.data);
                }
            }
        })
	}*/
};

Datafeeds.UDFCompatibleDatafeed.prototype.on = function(event, callback) {
    if (!this._callbacks.hasOwnProperty(event)) {
        this._callbacks[event] = [];
    }

    this._callbacks[event].push(callback);
    return this;
};

Datafeeds.UDFCompatibleDatafeed.prototype._fireEvent = function(event, argument) {
    if (this._callbacks.hasOwnProperty(event)) {
        let callbacksChain = this._callbacks[event];
        for (let i = 0; i < callbacksChain.length; ++i) {
            callbacksChain[i](argument);
        }

        this._callbacks[event] = [];
    }
};

Datafeeds.UDFCompatibleDatafeed.prototype.onInitialized = function() {
    this._initializationFinished = true;
    this._fireEvent('initialized');
};

Datafeeds.UDFCompatibleDatafeed.prototype._logMessage = function(message) {
    if (this._enableLogging) {
        let now = new Date();
        console.log(now.toLocaleTimeString() + '.' + now.getMilliseconds() + '> ' + message);
    }
};

Datafeeds.UDFCompatibleDatafeed.prototype._initialize = function () {
    this._configuration = this.defaultConfiguration();
    this.onInitialized();
	this._fireEvent('configuration_ready');
}

Datafeeds.UDFCompatibleDatafeed.prototype.onReady = function(callback) {
    let _this = this;

    if (this._configuration) {
        setTimeout(function() {
            callback(_this._configuration);
        }, 0);
    } else {
        this.on('configuration_ready', function() {
            callback(_this._configuration);
        });
    }
};

//	===============================================================================================================================
//	The functions set below is the implementation of JavaScript API.

Datafeeds.UDFCompatibleDatafeed.prototype.resolveSymbol = function(symbolName, onSymbolResolvedCallback, onResolveErrorCallback) {
	let _this = this;

	setTimeout(function() {
		onSymbolResolvedCallback(_this._symbolInfo);
	}, 0);
};
let index = 0;
Datafeeds.UDFCompatibleDatafeed.prototype.getBars = function(symbolInfo, resolution, rangeStartDate, rangeEndDate, onHistoryCallback, onErrorCallback,firstDataRequest=true) {
    //	timestamp sample: 1399939200

    if (rangeStartDate > 0 && (rangeStartDate + '').length > 10) {
        throw new Error(['Got a JS time instead of Unix one.', rangeStartDate, rangeEndDate]);
    }
    /*console.log(new Date(rangeStartDate*1000))
  console.log(new Date(rangeEndDate*1000))*/

/*    this.api.klineLastData({
      needTickers:1,
      symbol:'zbqc',
      type:resolution+'min',
      size:1000
    }).then(res=>{



    },res=>{
     // console.log(res)
    })*/
  let nodata = false;
  let bars = [];
   let datas = [
     {
       amount:0,
       count:72599.0382,
       dayTotalDealAmount:0,
       period:"1week",
       priceHigh:0.078088,
       priceLast:0.077432,
       priceLow:0.075971,
       priceOpen: 0.076152,
       symbolId:"ETH_BTC",
       time: 1527436800000,
       volume: 72599.0382
     },{
       amount:0,
       count:113603.982915,
       dayTotalDealAmount:0,
       period:"1week",
       priceHigh:0.080845,
       priceLast:0.079225,
       priceLow:0.077411,
       priceOpen:0.077432,
       symbolId:"ETH_BTC",
       time: 1528041600000,
       volume:113603.982915
     },{
       amount:0,
       count:3397.253445,
       dayTotalDealAmount:0,
       period:"1week",
       priceHigh:0.079123,
       priceLast:0.076553,
       priceLow:0.07236,
       priceOpen:0.077489,
       symbolId:"ETH_BTC",
       time:1528646400000,
       volume:3397.253445
     },{
       amount: 0,
       count: 5110.4693,
       dayTotalDealAmount: 0,
       period: "1week",
       priceHigh: 0.081,
       priceLast: 0.076675,
       priceLow: 0.075075,
       priceOpen: 0.076534,
       symbolId: "ETH_BTC",
       time: 1529251200000,
       volume: 5110.4693
     },{
       amount: 0,
       count: 0,
       dayTotalDealAmount: 0,
       period: "1week",
       priceHigh: 0.073271,
       priceLast: 0.073271,
       priceLow: 0.073271,
       priceOpen: 0.073271,
       symbolId: "ETH_BTC",
       time: 1529769600000,
       volume: 0
     }
   ]
  datas.forEach(item => {
    bars.push({
      time: item.time,
      open: item.priceOpen,
      close: item.priceLast,
      high: item.priceHigh,
      low: item.priceLow,
      volume: item.volume
    });
  })
  onHistoryCallback(bars,{ noData: false});


  /*DCTPAPI.trade_historyKLine({
        type: "POST",
        data: {
			virtualCoinId: symbolInfo.ticker,
			startTimeStamp: rangeStartDate,
			endTimeStamp: rangeEndDate,
			step: this.getStepByResolution(resolution)
        },
        success(result) {
            if (result.result) {
                let nodata = !result.data.length;
                let bars = [];

                result.data.forEach(item => {
                    bars.push({
                        time: item.timeStamp,
                        open: item.openPrice,
                        close: item.closePrice,
						high: item.highPrice,
                        low: item.lowPrice,
						volume: item.totalNumber
                    });
                })

				onDataCallback(bars, { noData: nodata });
            }
        },
        error(result) {
			console.warn(['getBars(): HTTP error', arg]);

			if (!!onErrorCallback) {
				onErrorCallback('network error: ' + JSON.stringify(arg));
			}
        }
    })*/
};

Datafeeds.UDFCompatibleDatafeed.prototype.subscribeBars = function(symbolInfo, resolution, onRealtimeCallback, listenerGUID, onResetCacheNeededCallback) {
    let _this = this;

    this._socket.send(symbolInfo, resolution, onRealtimeCallback, listenerGUID, onResetCacheNeededCallback)
};

Datafeeds.UDFCompatibleDatafeed.prototype.unsubscribeBars = function(listenerGUID) {
	this._socket.destroy();
};

Datafeeds.UDFCompatibleDatafeed.prototype.getStepByResolution = function (resolution) {
  //console.log(resolution)
    let step = parseFloat(resolution);
    let filter = resolution.toString().match(/[a-z]/i);

    if (isNaN(step)) {
        step = 1;
    }
    if (filter) {
        switch (filter[0].toUpperCase()) {
            case "D":
                step *= 24 * 60;
                break;
            case "W":
                step *= 7 * 24 *60;
                break;
            case "M":
                step *= 30 * 24 *60;
                break;
        }
    } else {
        step *= 1;
    }

    return step;
}

export default {
    UDFCompatibleDatafeed: Datafeeds.UDFCompatibleDatafeed
};
